<template>
  <ui-page
      class="order"
      :enable-refresh="true"
      @scrolltolower="handleScrollToLower"
      @refresh="handlePageRefresh"
  >
    <ui-filter :value="filters" slot="filter" >
      <ui-filter-group>
        <ui-filter-item>
          <view class="order__filter-item-label">
            <ui-textbox style="border-radius: 10rpx;" @input="handleFilterChange"
                        v-model="filters.queryParam"
                        :placeholder="$t('search_placeholder')"
            ></ui-textbox>
          </view>
        </ui-filter-item>
        <ui-filter-item>
          <view class="mine-people__action"
                @click="handleAddClick">
            <bi-icon-button
                type="warning"
                size="mini"
                :icon="'https://hsmw-tool-pic-1303885219.cos.ap-beijing.myqcloud.com/weapp/files/htn/plus.png'"
            ></bi-icon-button>
            <text style="color: #F18662;font-size: 24rpx">{{ $t('submit_delivery_order') }}</text>
          </view>
        </ui-filter-item>
        <ui-filter-item>
          <view class="mine-people__action"
                @click="handleanalysisClick">
            <bi-icon-button
                type="warning"
                size="mini"
                :icon="'https://aiduk-1334050802.cos.ap-guangzhou.myqcloud.com/ztc/icons/analisys.png'"
            ></bi-icon-button>
            <text style="color: #F18662;font-size: 24rpx;text-align: center">{{ $t('order-tongji') }}</text>
          </view>
        </ui-filter-item>
      </ui-filter-group>
      <ui-filter-group>
        <ui-filter-item  >
          <view style="left: 0rpx;right: 0rpx">
            <order-items  v-model="filters.orderStatus"  :items="typeItems"  :scope="tabbarScope"  @input="handleStatusFilterChange"  >
<!--              <view class="" slot="item" slot-scope="{ item, scope ,orderCount}">
                <text class="">{{ item.label }} </text> {{orderCount.goingCount}}
                <text  class="order__tabbar-item-badge" >{{orderCount.goingCount}}</text>
              </view>-->
            </order-items>
          </view>
        </ui-filter-item>
      </ui-filter-group>
      <ui-filter-group v-show="filters.orderStatus=='1'">
        <ui-filter-item>
          <view class="order__complete-filter">
            <radio-group>
              <radio color="#FF6B48" @input="handleStatusChange" @click="handleTypeRadioClick(item)" v-for="(item,index) in typeItem" class="radio-item" :value="item.value" :checked="item.isCheck" >{{item.name}}</radio>
            </radio-group>
          </view>
        </ui-filter-item>
      </ui-filter-group>
    </ui-filter>
    <ui-load-data
        ref="dataList"
        :page-size="10"
        :more-offset="-16"
        @query="handleQueryData"
        v-model="orderData"
    >
      <bi-order-delivery-card
          v-for="(item, index) in orderData"
          :key="index"
          :data="item"
          @click="handleOrderItemClick(item)"
          :current-time-type="currentTimeType"
      >
        <template slot="toolbar">
          <view class="order__toolbar" @click.stop>
            <!-- 使用 flex 布局容器 -->
            <view class="order__toolbar-actions">
              <ui-toolbar :padding="false">
                <ui-toolbar-item v-if="canDelete(item)">
                  <view class="toolbar-btn delete-btn" @click="handlDeleteOrderClick(item)">
                    <text class="iconfont icon-delete" style="margin-right: 8rpx;"></text>{{ $t('delete_order') }}
                  </view>
                </ui-toolbar-item>

                <ui-toolbar-item >
                  <view class="toolbar-btn detail-btn" @click="handleOrderItemClick(item)">
                    <text class="iconfont icon-eye" style="margin-right: 8rpx;"></text>{{ $t('view_details') }}
                  </view>
                </ui-toolbar-item>

                <ui-toolbar-item  v-if="canEdit(item)">
                  <view class="toolbar-btn edit-btn" @click="handleUpdateClick(item)">
                    <text class="iconfont icon-edit" style="margin-right: 10rpx;"></text>
                    {{ editBtnText(item) }}
                  </view>
                </ui-toolbar-item>
              </ui-toolbar>
            </view>
          </view>
        </template>
      </bi-order-delivery-card>
    </ui-load-data>
    <template slot="body">
      <view class="order__follow-official" v-if="!checkFlag">
        <bi-follow-official-account :shadow="true"></bi-follow-official-account>
      </view>
    </template>
  </ui-page>
</template>
<script>
import { loadDeliveryOrderListData} from '@/apis/order.js';
import BiOrderDeliveryCard from '@/common/order-delivery-card/order-delivery-card.vue';
import { buildUrl } from '@/utils/url.js';
import { getShareData } from '@/utils/share.js';
import BiShareButton from '@/common/share-button/share-button.vue';
import BiFollowOfficialAccount from '@/common/follow-official-account/follow-official-account.vue';
import Event from '@/utils/event.js';
import OrderItems  from  '@/common/items-order/order-items.vue';
import storage from '@/utils/storage'
import BiIconButton from '@/common/icon-button/icon-button.vue';
export default {
  components: {
    OrderItems,
    BiOrderDeliveryCard,
    BiShareButton,
    BiFollowOfficialAccount,
    BiIconButton
  },
  data() {
    return {
      shouldReload: true,
      count:1,
      currentTimeType:null,
      orderData:[],
      indexMapImage: 'https://hsmw-tool-pic-1303885219.cos.ap-beijing.myqcloud.com/weapp/files/htn/map-pin.png',
      checkFlag:true,
      radioList: [{
        value: '1',
        name: this.$t('all'),
        isCheck: true
      }, {
        value: '2',
        name: this.$t('view_rental_orders')
      }, {
        value: '3',
        name: this.$t('view_own_orders')
      }],
      checkRadio: false,
      tabbarScope: {
        badgeIndex:0,
        unrecieved: 0
      },
      completeFilters: {
        notFilled: false
      },
      queryParam: null,
      filters: {
        queryParam: null,
        orderType:1,
        orderStatus:1,
        vehicleYears:null,
        chassis:null,
        vehicleType:null,
        markPrice:null,
        vehicleModel:null,
        vehicleBrand:null,
        vehicleLocaltion:null,
        orderStatusType:null
      }
    };
  },
  watch: {
    qu(newValue, oldValue) {
      console.log('消息从', oldValue, '变成了', newValue);
    }
  },
  computed: {
    orderTypeItems() {
      return [
        {
          label: '自有车订单',
          name: '0'
        },
        {
          label: '外租车订单',
          name: '1'
        }
      ];
    },
    typeItem() {
      return [
        {
          name: this.$t('all_order'),
          value: null,
          isCheck:true
        },
        {
          name: this.$t('vehicle_arrived_warehouse'),
          value: 1,
        },
        {
          name:  this.$t('loading_completed'),
          value: 3
        },
        {
          name:  this.$t('already_departed'),
          value: 4
        }
      ];
    },
    typeItems() {
      return [
        {
          label: this.$t('processing'),
          name: '1',
          badge: this.tabbarScope.badgeIndex,
          },
        {
          label: this.$t('completed'),
          name: '2',
          badge:this.tabbarScope.unrecieved

        },
        {
          label: this.$t('deleted'),
          name: '3',
          badge: 0
        }
      ];
    },
  },
  onLoad(urlParams) {
    // 初始化语言
    let savedLanguage = uni.getStorageSync('language') || 'zh';
    const currentTimeType = storage.get('CURRENT_TIME_TYPE');
    savedLanguage=(currentTimeType === 1 || currentTimeType === '1') ? 'en' : 'zh';
    if (savedLanguage) {
      this.$i18n.locale = savedLanguage;
    }
    console.log('urlParams--currentTimeType', storage.get('CURRENT_TIME_TYPE'))
    if(urlParams && urlParams.vehicleType){
      this.filters.vehicleType=urlParams.vehicleType
    }
    if(urlParams && urlParams.orderType){
      this.filters.orderType=urlParams.orderType
    }
  },
  onShareAppMessage() {
    return getShareData();
  },
  onShow() {
    if (this.shouldReload) {
      this.$refs.dataList && this.$refs.dataList.reload();
    }
    // 重置刷新标志
    this.shouldReload = true;
    this.currentTimeType = storage.get('CURRENT_TIME_TYPE');
  },
  methods: {
    handleStatusChange(){
      this.$refs.dataList.reload();
    },
    handleTypeRadioClick(item){
      this.filters.orderStatusType=item.value
      this.$refs.dataList.reload();
    },
    // 是否允许查看详情
    canDetail(item) {
      return true; // 所有状态都可查看
    },

    // 是否允许删除
    canDelete(item) {
      return ![6, 7].includes(item.orderStatus);
    },

    // 是否允许编辑
    canEdit(item) {
      return ([1, 2, 3, 4, 5].includes(item.orderStatus)) || (item.orderStatus === 6 && item.unReceiveCount >0);
    },
    // 动态返回编辑文案
    editBtnText(item) {
      if (item.orderStatus === 4 || item.orderStatus === 5) {
        if (item.unPodCount > 0) {
          return this.$t('upload_pod');
        } else {
          return this.$t('complete_order');
        }
      } else {
        return this.$t('continue_upload');
      }
    },
    handleAddClick(){
      uni.navigateTo({
        url: '/packages/mine/order/order-delivery/order-delivery-create'
      })
    },
    handleanalysisClick(){
      uni.navigateTo({
        url: '/packages/mine/order/order-delivery/analysis/analysis-delivery'
      })
    },
    clearFilter(){
      console.log('clearFilter')
      this.filters={};
    },
    handleRadioClick(item){
      if(item.value==='1'){
        this.outsideLeasingFlag = '';
      }else if(item.value==='2'){
        this.outsideLeasingFlag = 1;
      }else{
        this.outsideLeasingFlag = 0;
      }
      this.$refs.dataList.reload();
    },
    handlDeleteOrderClick(item) {
      uni.showModal({
        "cancelText": this.$t('cancel'),
        'confirmText': this.$t('confirm'),
        'confirmColor': "#F18662",
        'content': this.$t('confirm_delete_order'),
        'success': (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: buildUrl('/packages/mine/order/order-delivery/order-cancel', {
                id: item.id,
                eventName: this.cancelOrderEvent,
                orderType: item.orderType
              })
            });
            /*           */
            this.shouldReload = true;
          }
        }
      })
    },
    handlePageRefresh({ setCallback }) {
      setCallback(() => {
        return this.$refs.dataList && this.$refs.dataList.reload();
        this.currentTimeType=storage.get('CURRENT_TIME_TYPE')
      });
    },
    handleScrollToLower() {
      this.$refs.dataList && this.$refs.dataList.loadMore();
      this.currentTimeType=storage.get('CURRENT_TIME_TYPE')
    },
    handleQueryChange(){
      console.log('handleQueryChange', this.filters.queryParam)
    },
    handleStatusFilterChange() {
      setTimeout(() => {
        this.$refs.dataList && this.$refs.dataList.reload()
      }, 300)
    },
    handleFilterChange() {
      setTimeout(() => {
        this.$refs.dataList && this.$refs.dataList.reload()
      }, 300)
    },
    handleRenderSharePath(item) {
      uni.navigateTo({
        url: buildUrl('/packages/vehicle/vehicle-detail/vehicle-detail', {
          id: item.vehicleId,
          eventName: this.changeEventName,
          data:JSON.stringify(item),
          behavior: 'order'
        })
      });
    },
    handleOrderItemClick(item) {
      this.shouldReload = false;
      uni.navigateTo({
        url: buildUrl('/packages/mine/order/order-delivery/order-delivery-detail', {
          id: item.id,
          eventName: this.changeEventName,
          behavior: 'order',
          currentTimeType:this.currentTimeType
        })
      });
    },
    handleQueryData({ setCallback }) {
      setCallback((params) => {
        let nextParams = {};
        nextParams = Object.assign({}, params, this.filters, {
          outsideLeasingFlag: this.outsideLeasingFlag
        });
        this.lastRequest = loadDeliveryOrderListData(nextParams);
        return this.lastRequest
            .then((rs) => {
              let res = rs.records;
              console.log('rs', rs)
              if (res) {
                if (this.filters.orderStatus === '1' || this.filters.orderStatus === 1) {
                  this.tabbarScope.badgeIndex = rs?.total || 0;
                }
              }
              let unReceiveOrderCount = 0;
              if (res && res.length > 0) {
                res.forEach(order => {
                  // 如果 order.orderInfoList 存在，则遍历它
                  if (order.orderInfoList && Array.isArray(order.orderInfoList)) {
                    let unPodCount = 0;
                    let unReceiveCount = 0;
                    order.orderInfoList.forEach(info => {
                      // 判断 podOrderPictures 是否为空
                      if (info.podPicCount > 0) {
                        unPodCount++;
                      }
                      if (info.receiveFlag === 0 && info.codFlag===1) {
                        unReceiveCount++;
                      }
                    });
                    order.unPodCount = order.detailCount - unPodCount
                    order.unReceiveCount = unReceiveCount
                    order.orderCount = (order.orderInfoList.length)
                    if (order.unReceiveCount > 0) {
                      unReceiveOrderCount++;
                    }
                  }
                });
                // 按 unReceiveCount 排序，未收货的排在前面
                res.sort((a, b) => {
                  if (a.unReceiveCount > 0 && b.unReceiveCount === 0) {
                       return -1; // a排在b前面
                   } else if (a.unReceiveCount === 0 && b.unReceiveCount > 0) {
                       return 1;  // b排在a前面
                   } else {
                     return 0;  // 保持原有顺序
                  }
                });
              }
              if (this.filters.orderStatus === '2' || this.filters.orderStatus === 2) {
                this.tabbarScope.unrecieved = rs.total;
              }
              return rs.records;
            })
            .finally(() => {
              this.lastRequest = null;
            });
      });
    },
    handleUpdateClick(item) {
      this.currentRow = item;
      uni.navigateTo({
        url:buildUrl( '/packages/mine/order/order-delivery/order-delivery-create',{
          id:this.currentRow.id,
          amend:true,
        })
      })
      this.shouldReload = true;
    },
    handleUpdateInfoClick(){
      uni.navigateTo({
        url:buildUrl( '/packages/mine/order/order-create',{
          id:this.currentRow.id,
          amend:true
        })
      })
      this.shouldReload = true
      this.$refs.orderActionSheet.close();
    },
    handleUpdateCarClick() {
      this.$refs.orderActionSheet.close();
      uni.navigateTo({
        url: buildUrl('/packages/order/order-update-car/order-update-car', {
          id: this.currentRow.id,
          eventName: this.updateCarEventName
        })
      });
    },
  },
  beforeDestroy() {
    Event.off(this.cancelOrderEvent);
    Event.off(this.updateCarEventName);
    Event.off(this.changeEventName);
  },
};
</script>
<style lang="less">
@import '/static/css/common-styles.css';
@import '/static/css/loading-animations.css';
@import '/static/css/filter-styles.css';
</style>

<style lang="less">.order__toolbar {
  padding-top: 15rpx;
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.order__tabbar-item-badge {
  display: inline-block;
  height: 35rpx;
  line-height: 35rpx;
  color: #fff;
  background-color: #c00;
  padding: 0 10rpx;
  border-radius: 20rpx;
  font-size: 25rpx;
  vertical-align: top;
  margin-top: 6rpx;
  margin-left: 6rpx;
}

.order__tabbar-item-text {
  font-size: 28rpx;
  font-weight: 700;
  transform: scale(0.8);
}

.order__toolbar-right .order__toolbar-item {
  margin: 0 10rpx;
}

.order__toolbar-right .order__toolbar-item .delete-btn {
  background-color: #e74c3c;
  color: white;
}

.order__toolbar-right .order__toolbar-item .edit-btn {
  background-color: #28a745;
  color: white;
  margin-right: 20rpx;
}

.order__toolbar-right .order__toolbar-item view {
  border-radius: 15rpx;
  font-size: 25rpx;
  padding: 6rpx 15rpx;
  color: white;
  display: inline-block;
  text-align: center;
}

.detail-btn {
  background-color: #409eff;
}

.delete-btn {
  background-color: #e74c3c;
}

.iconfont {
  margin-right: 8rpx;
  font-size: 26rpx;
  line-height: 26rpx;
}

.order__toolbar-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: auto;
  min-width: fit-content;
  flex-wrap: nowrap;
  gap: 10rpx;
  margin-left: auto;
  padding-right: 10rpx;
}

.edit-btn {
  background-color: #28a745;
  padding: 5rpx 8rpx;
  font-size: 25rpx;
  min-width: 85rpx;
  margin-right: 60rpx;
}

.order {
  margin-top: 30rpx;
}

.order__toolbar-wrapper {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  overflow-x: hidden;
}

@media (max-width: 750rpx) {
  .order__toolbar-actions {
    gap: 6rpx;
  }

  .toolbar-btn {
    padding: 6rpx 12rpx;
    font-size: 22rpx;
    height: 42rpx;
  }
}

.order__toolbar-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: auto;
  min-width: fit-content;
  flex-wrap: nowrap;
  gap: 6rpx;
  margin-left: auto;
  padding-right: 10rpx;
}

.toolbar-btn {
  margin-left: 6rpx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 5rpx 15rpx;
  height: 42rpx;
  font-size: 25rpx;
  border-radius: 10rpx;
  color: white;
  white-space: nowrap;
  word-break: keep-all;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: auto;
  flex: 0 0 auto;
  box-sizing: border-box;
}
.mine-people__action {
  width: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;

  text {
    text-align: center;
    display: block;
    width: 100%;
  }
}
.order__complete-filter {
  padding: 6px 0 16px 0;
  margin-bottom: -8px;
}
.radio-item{
  transform: scale(0.8);
  font-size: 28rpx;
  font-weight: bold;
}
</style>
